package com.lovezy.platform.topic.video;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lovezy.platform.core.base.AppServer;
import com.lovezy.platform.core.codec.CodecUtil;
import com.lovezy.platform.core.exception.ServiceException;
import com.lovezy.platform.filestore.service.FileHelper;
import com.lovezy.platform.filestore.vo.FileVo;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.net.URL;

/**
 * BILIBILI 处理类
 * Created by jin on 2017/12/21.
 */
@Component("biliTopicHandler")
public class BiliTopicHandler extends BaseTopicSourceHandler{

    @Autowired
    private Bilibili bilibili;

    @Autowired
    private AppServer appServer;

    @Autowired
    private FileHelper fileHelper;

    @Override
    public String getCover(String aId) {
        if (aId == null) {
            return null;
        }
        String jsonResult = bilibili.videoCover(aId);
        ObjectMapper om = new ObjectMapper();
        try {
            JsonNode jsonNode = om.readTree(jsonResult);
            JsonNode result = jsonNode.get("Result").get("VideoInfo").get("PicUrl");
            String picUrl = result.asText();
            URL url = new URL(picUrl);
            String fileExtension = fileHelper.getFileExtension(picUrl);
            File picFile = new File(appServer.getFileTempPath()  + CodecUtil.uuid() + fileExtension);
            FileUtils.copyURLToFile(url,picFile);
            FileVo fileVo = fileService.uploadFile(picFile, appServer.getAdmin());
            return fileVo.getUrl();
        } catch (Exception e) {
            log.error("读取哔哩哔哩API数据失败", e);
            throw new ServiceException("读取哔哩哔哩API数据失败");
        }
    }
}
